<template>
  <div>
    <!-- 面包屑 区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card" style="margin-top: 10px">
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRolesActive">添加角色</el-button>
        </el-col>
      </el-row>
      <!--  展开列-->
      <el-table :data="rolesList" stripe border style="width: 100%">
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row
              v-for="(item, index) in scope.row.children"
              :key="item.id"
              :class="['vcenter', index === 0 ? '' : 'btop']"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeRules(scope.row, item.id)">{{
                  item.authName
                }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级三级权限 -->
              <el-col :span="19">
                <el-row
                  v-for="(item2, index) in item.children"
                  :key="item2.id"
                  :class="['bbottom', index === 0 ? 'btop' : '', 'vcenter']"
                >
                  <!-- 二级权限-->
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRules(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRules(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 角色列表  -->
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="roleName" label="角色名称"> </el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
        <el-table-column prop="children">
          <template v-slot="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="small"
              @click="addModifyRoles(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="small"
              @click="deleteRoles(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="small"
              @click="setRolesDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色区域 -->
    <el-dialog
      title="提示"
      :visible.sync="dialogRoles"
      width="30%"
      @close="closeAddRoles"
    >
      <el-form
        ref="Rolesform"
        :model="addRoles"
        :rules="rolesRules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoles.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoles.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogRoles = false">取 消</el-button>
        <el-button type="primary" @click="submitAddRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色区域 -->
    <el-dialog title="提示" :visible.sync="modifyDialog" width="30%">
      <el-form
        ref="modifyRolesRef"
        :model="modifyRoles"
        :rules="modifyRulesRules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="modifyRoles.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="modifyRoles.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="modifyDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitModifyRoles(modifyRoles.roleId)"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 设置权限的区域 -->
    <el-dialog title="提示" :visible.sync="setRolesDialogVisible" width="30%" @close="setcloseRolesDIalog">
     <el-tree :data="setRoles" ref="setRolesDialog" :props="setRolesProps" show-checkbox
       node-key="id" :default-expand-all="true"  :default-checked-keys="defaultKeys"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sumbitRoles"
           >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      rolesList: [],
      // 是否显示添加角色对话框
      dialogRoles: false,
      // 添加角色的数据
      addRoles: {
        roleName: '',
        roleDesc: ''
      },
      rolesRules: {
        roleName: [
          {
            required: true,
            trigger: 'blur'
          }
        ],
        roleDesc: [
          {
            required: true,
            trigger: 'blur'
          }
        ]
      },
      // 修改角色数据
      modifyRoles: {},
      // 修改角色规则
      modifyRulesRules: {},
      // 是否显示修改角色对话框
      modifyDialog: false,
      // 是否显示添加角色权限的对话框
      setRolesDialogVisible: false,
      // 获取设置角色权限的数据
      setRoles: [],
      // 树形控件属性绑定对象
      setRolesProps: {
        // 看到的文本是什么数据字段
        label: 'authName',
        // 来实现数据嵌套
        children: 'children'

      },
      // 默认展示所有选中节点的key值
      defaultKeys: [],
      // 提交的id
      submitid: ''
    }
  },
  created () {
    this.getRolesList()
  },
  methods: {
    // 获取数据
    async getRolesList () {
      const { data: res } = await this.$http.get('/roles')
      if (res.meta.status !== 200) {
        return this.$message.error('访问失败')
      }
      this.rolesList = res.data
      console.log(this.rolesList)
    },
    // 弹出添加角色对话框
    addRolesActive () {
      this.dialogRoles = !this.dialogRoles
    },
    // 关闭对话框重置表单
    closeAddRoles () {
      this.$refs.Rolesform.resetFields()
    },
    // 提交添加角色表单
    async submitAddRoles () {
      console.log('AA')
      const { data: res } = await this.$http.post('/roles', this.addRoles)
      console.log(res)
      if (res.meta.status !== 201) {
        return this.$message.error('提交失败')
      }
      this.$message.success('添加成功')
      // 关闭对话框
      this.dialogRoles = false
      // 刷新列表数据
      this.getRolesList()
    },
    // 删除角色
    async deleteRoles (id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`roles/${id}`)
        if (res.meta.status !== 200) {
          return this.$message.error('删除失败')
        }
        this.getRolesList()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 弹出修改角色对话框
    async addModifyRoles (id) {
      // 通过id查询数据
      const { data: res } = await this.$http.get(`/roles/${id}`)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取信息失败')
      }
      this.modifyRoles = res.data
      console.log(this.modifyRoles)
      this.modifyDialog = !this.modifyDialog
    },
    // 修改角色
    async submitModifyRoles (id) {
      this.$refs.modifyRolesRef
        .validate()
        .then(async () => {
          const { data: res } = await this.$http.put(
            `/roles/${id}`,
            this.modifyRoles
          )
          if (res.meta.status !== 200) {
            return this.$message.error('修改失败')
          }
          this.modifyDialog = !this.modifyDialog
          this.getRolesList()
          this.$message.success('修改成功')
        })
        .catch(() => {
          return this.$message.error('修改失败')
        })
    },
    // 移除权限
    removeRules (roles, rolesId) {
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `roles/${roles.id}/rights/${rolesId}`
          )
          if (res.meta.status !== 200) {
            return this.$message.error('删除权限失败')
          }
          // 重新赋值防止重新渲染没有打开
          roles.children = res.data
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 是否显示添加权限的对话框
    async setRolesDialog (roles) {
      this.submitid = roles.id
      // 获取角色权限数据
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败')
      }
      this.setRoles = res.data
      console.log(this.setRoles)
      this.getThreeRolesList(roles, this.defaultKeys)
      this.setRolesDialogVisible = true
    },
    // 通过递归的方式获取三级权限节点
    getThreeRolesList (node, arr) {
      // 如果当前节点不包含childen属性则保存
      if (!node.children) {
        return arr.push(node.id)
      }
      // 继续回掉
      node.children.forEach(item => {
        this.getThreeRolesList(item, arr)
      })
    },
    // 关闭获取角色权限的对话框
    setcloseRolesDIalog () {
      this.defaultKeys = []
    },
    // 提交获取权限的方法
    async sumbitRoles () {
      const keys = [
        ...this.$refs.setRolesDialog.getCheckedKeys(),
        ...this.$refs.setRolesDialog.getHalfCheckedKeys()
      ]
      const rights = keys.join(',')

      console.log(this.submitid)
      const { data: res } = await this.$http.post(`roles/${this.submitid}/rights`, { rids: rights })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('提交失败')
      }
      this.setRolesDialogVisible = false
      this.getRolesList()
      this.$message.success('提交成功')
    }
  }
}
</script>
<style   scoped>
.el-tag {
  margin: 5px;
}
.btop {
  border-top: 1px solid #eeee;
}
.bbottom {
  border-bottom: 1px solid #eeee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
